<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2015 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi.cn@gmail.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Com;

class DingMiandengAuth {
    
    /* 消息类型常量 */
    const MSG_TYPE_TEXT       = 'text';
    const MSG_TYPE_IMAGE      = 'image';
    const MSG_TYPE_VOICE      = 'voice';
    const MSG_TYPE_VIDEO      = 'video';
    const MSG_TYPE_SHORTVIDEO = 'shortvideo';
    const MSG_TYPE_LOCATION   = 'location';
    const MSG_TYPE_LINK       = 'link';
    const MSG_TYPE_MUSIC      = 'music';
    const MSG_TYPE_NEWS       = 'news';
    const MSG_TYPE_EVENT      = 'event';
    
    /* 二维码类型常量 */
    const QR_SCENE       = 'QR_SCENE';
    const QR_LIMIT_SCENE = 'QR_LIMIT_SCENE';

    /**
     * 微信开发者申请的appID
     * @var string
     */
    private $appid = '';

    /**
     * 微信开发者申请的appSecret
     * @var string
     */
    private $appsecret = '';

    /**
     * 获取到的access_token
     * @var string
     */
    private $accessToken = '';

    /**
     * api根路径
     * @var string
     */
    private $apiURL = 'https://oapi.dingtalk.com';

    /**
     * 构造方法，调用微信高级接口时实例化SDK
     * @param string $appid  微信appid
     * @param string $secret 微信appsecret
     * @param string $token  获取到的access_token
     */
    public function __construct($appid, $appsecret, $token = null){
        if($appid && $appsecret){
            $this->appid     = $appid;
            $this->appsecret = $appsecret;

            if(!empty($token)){
                $this->accessToken = $token;
            }
        } else {
            throw new \Exception('缺少参数appid 和 appsecret!');
        }
    }
    /**
     * 获取access_token，用于后续接口访问
     * @return array access_token信息，包含 token 和有效期
     */
    public function getAccessToken(){
        $param = array(
            'appid'  => $this->appid,
            'appsecret' => $this->appsecret
        );     
        $url = "{$this->apiURL}/sns/gettoken"; 
               
        $token = self::http($url, $param); 
        $token = json_decode($token, true);		
        if(is_array($token)){
            if($token['errcode']){
                throw new \Exception($token['errmsg']);
            } else {
                $this->accessToken = $token['access_token'];
                return $token;
            }
        } else {
            throw new \Exception('获取access_token失败！');
        }
    }
    
   
    /**
     * 获取钉钉返回
     * 向钉钉发送请求
     */
    public function getDingRe($name, $data = '', $method = 'GET', $param = '',$map=array(), $json = true){
    	$con=$this->api($name, $data, $method , $param , $json );
    	return $con;
    }
   
    /**
     * 调用微信api获取响应数据
     * @param  string $name   API名称
     * @param  string $data   POST请求数据
     * @param  string $method 请求方式
     * @param  string $param  GET请求参数
     * @return array          api返回结果
     */
    protected function api($name, $data = '', $method = 'GET', $param = '', $json = true){
        $params = array('access_token' => $this->accessToken);
        if(!empty($param) && is_array($param)){
            $params = array_merge($params, $param);
        }
        $url  = "{$this->apiURL}/{$name}"; 
        if($json && !empty($data)){
            //保护中文，微信api不支持中文转义的json结构
            array_walk_recursive($data, function(&$value){
                $value = urlencode($value);
            });
            $data = urldecode(json_encode($data));
        }
		$data = self::http($url, $params, $data, $method);		    
        return json_decode($data, true);
    }
    /**
     * 发送HTTP请求方法，目前只支持CURL发送请求
     * @param  string $url    请求URL
     * @param  array  $param  GET参数数组
     * @param  array  $data   POST的数据，GET请求时该参数无效
     * @param  string $method 请求方法GET/POST
     * @return array          响应数据
     */
    protected static function http($url, $param, $data = '', $method = 'GET'){
    	
        $opts = array(
            CURLOPT_TIMEOUT        => 100,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        );
        /*根据请求类型设置特定参数 */
        $opts[CURLOPT_URL] = $url . '?' . http_build_query($param);     
       
        if(strtoupper($method) == 'POST'){
            $data= preg_replace("/\s|　/","",$data);
            //$data=json_decode(trim($data));
           // print_r($data);
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $data;
            if(is_string($data)){ //发送JSON数据
                $opts[CURLOPT_HTTPHEADER] = array(
                    'Content-Type: application/json; charset=utf-8',  
                    'Content-Length: ' . strlen($data),
                );
            }
        } 
        /* 初始化并执行curl请求 */
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data  = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        //发生错误，抛出异常
        if($error) throw new \Exception('请求发生错误：' . $error);
        
        return  $data;
    }    
}
